# coding:utf-8
class Admin::AccountsController < AdminController
	
  respond_to :html, :json

  set_tab :business

  before_filter :setup, only: [:index]

  def index
    @accounts = Account
    @accounts = @accounts.where(account_group_id: params[:account][:account_group]) if params[:account][:account_group].present?
    @accounts = @accounts.where(mobile_number: params[:account][:mobile_number]) if params[:account][:mobile_number].present?
    @accounts = @accounts.after_date(params[:account][:start_date]) if params[:account][:start_date].present?
    @accounts = @accounts.before_date(params[:account][:end_date]) if params[:account][:end_date].present?

    respond_to do |format|
      format.html {

        if @account_group
          eval %{ set_tab :account_group_#{@account_group.id}, :sub_nav }
        else
          set_tab :accounts, :sub_nav
        end
        @accounts = @accounts.includes(:account_group,:register_terminal).order(sort_column + " " + sort_direction).page(params[:page])

      }
      format.js {
        if params[:chart]
          if @accounts.all.size > 0
            @accounts = @accounts.total_counts_by(params[:account][:date_part])
            @chart_attrs = get_line_chart_attrs(@accounts)
          end
        else
          @accounts = @accounts.order(sort_column + " " + sort_direction).page(params[:page])
        end
      }
      format.csv {
        send_data(csv_content_for(@accounts),  
          :type => "text/csv;charset=utf-8; header=present",  
          :filename => "账号统计_#{Time.now.strftime("%Y%m%d")}.csv") 
      }
    end
	end

  def new
    @account = Account.new(account_group_id: params[:account_group_id])
  end

  def edit
    @account = Account.find params[:id]
  end

  def create
    @account = Account.new(params[:account])
    render :action => :new  unless @account.save
  end

  def update
    @account = Account.find params[:id]
    render :action => :edit unless @account.update_attributes(params[:account])
  end

  def destroy
    @account = Account.find params[:id]
    @account.destroy
  end

  def export
    respond_to do |format|
      format.csv {   
        send_data Account.to_csv,:type => "text/csv;charset=utf-8; header=present",  
          :filename => "账户模板_#{Time.now.strftime("%Y%m%d")}.csv"
      }
    end
  end

  def import
    @notice
    begin
      Account.import(params[:file],params[:account_group_id])
      @success = "工单导入成功."
    rescue => e
      @error = e
    end
    redirect_to admin_accounts_url(account: {account_group: params[:account_group_id]}), :flash => { error: @error.to_s, success: @success }
  end

  private

  def setup
    params[:account] = params[:account] || {}
    if params[:account][:account_group].present?
      @account_group = AccountGroup.where(id: params[:account][:account_group]).first
      @ways = ["业务","用户分组管理",@account_group.group_name]
    else
      @ways = ["业务","用户管理"]
    end
    
    @left_panel = "layouts/account_widget"
  end

  def get_line_chart_attrs(accounts)
    chart_attrs = {:type => 'line'}
    chart_attrs[:title] = "注册统计"
    chart_attrs[:name] = "注册统计"
    chart_attrs[:uom] = '次数'
    chart_attrs[:xaxis] = []
    chart_attrs[:datas] = {'注册用户数' => []}
    accounts.reverse.to_a.each do |account|
      if params[:account][:date_part] != 'year'
        chart_attrs[:xaxis] << [account.created_year,account.created_part] unless chart_attrs[:xaxis].include?([account.created_year,account.created_part])
      else
        chart_attrs[:xaxis] << account.created_year unless chart_attrs[:xaxis].include?(account.created_year)
      end
      chart_attrs[:datas]['注册用户数'] << account.total
    end
    xaxis = chart_attrs[:xaxis]
    case params[:account][:date_part] when 'week','month'
      chart_attrs[:xaxis] = xaxis.collect{|xax| "#{xax[0]}-#{xax[1]}#{date_parts[params[:account][:date_part]]}" }
    when 'day'
      chart_attrs[:xaxis] = xaxis.collect{|xax| "#{xax[1]}" }
    when 'year'
      chart_attrs[:xaxis] = xaxis.collect{|xax| "#{xax}" }
    end
    chart_attrs
  end

  def csv_content_for(objs)
    CSV.generate do |csv|
      csv << ["\xEF\xBB\xBF手机号", "姓名", "签到次数","推荐"]
      objs.each do |record|  
        csv_td = [  
          record.mobile_number,  
          record.name,
          record.account_signin_counter,
          record.recommand_count,
        ]
        csv << csv_td
      end
      csv
    end
  end

end